package com.cxs.xiaomi.utils;

import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/*
 * @Author:cxs
 * @Date:2021/9/15  21:08
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * 文件操作工具类
 * */
public class FileUploadUtil {
    /**
     * 文件上传
     * @param part 媒体对象
     * @param basePath 基础路径
     * @return 绝对路径 - 基础路径, URLEncoder后的路径
     */
    public static String upload(Part part,String basePath){
        File file = new File(basePath);
        if(!file.exists()){
            file.mkdirs();
        }
        String fileParentPath = createNewFilePath(basePath);
        String submittedFileName = part.getSubmittedFileName();
        if(submittedFileName != null){
            // 没传图片
            if("".equals(submittedFileName)){
                return null;
            }
            String fileName = createFileName() + submittedFileName.substring(submittedFileName.lastIndexOf("."));
            // 穿了图片
            String fileRealPath =basePath + File.separator + fileParentPath +
                    File.separator + fileName;
            try {
                part.write(fileRealPath);
                part.delete();
                return URLEncoder.encode(fileParentPath + File.separator + fileName,"utf-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 创建目录
    public static String createNewFilePath(String basePath){
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
        String filePath = sdf.format(new Date());
        String newFilePath = basePath + File.separator + filePath;
        File file = new File(newFilePath);
        if(!file.exists()){
            file.mkdir();
        }
        return filePath;
    }
    // 创建文件名
    public static String createFileName(){
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmss");
        return UUID.randomUUID()
                .toString()
                .replaceAll("-","")
                .substring(0,15) + sdf.format(new Date());
    }

    // 删除文件
    public static boolean removeFile(String basePath,String filePath){
        try {
            String decodeFilePath = URLDecoder.decode(filePath, "utf-8");
            String fileRealPath = basePath + File.separator + decodeFilePath;
            File file = new File(fileRealPath);
            if(file.exists()){
                return file.delete();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }
}
